from typing import Dict, Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from core.pagination import paging_data, _CustomPageParams
from fastapi import HTTPException, status

from modules.customer_info.models.customer_info_model import CustomerInfo
from modules.customer_info.schemas.customer_info_schema import CustomerInfoCreate, CustomerInfoUpdate
from modules.customer_info.params.customer_info_params import CustomerInfoQuery
from modules.customer_info.curd.customer_info_curd import customer_info_dao
from utils.query_builder import build_select_stmt


class CustomerInfoService:
    @staticmethod
    async def get_list_with_pagination(db: AsyncSession, query_params: CustomerInfoQuery) -> Dict[str, Any]:
        stmt = build_select_stmt(
            CustomerInfo,
            query_params,
            order_by_desc="id",
            text_like_fields=None,
        )
        params = _CustomPageParams(page=query_params.page, size=query_params.size)
        return await paging_data(db, stmt, params=params)

    @staticmethod
    async def get_by_id(db: AsyncSession, pk: Any) -> Optional[CustomerInfo]:
        repo = await customer_info_dao.get_by_id(db, pk)
        return repo

    @staticmethod
    async def create(db: AsyncSession, data: CustomerInfoCreate) -> CustomerInfo:
        repo = await customer_info_dao.create(db, data)
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def update(db: AsyncSession, pk: Any, data: CustomerInfoUpdate) -> Optional[CustomerInfo]:
        repo = await customer_info_dao.update(db, pk, data)
        if not repo:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"记录 {pk} 不存在")
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def delete(db: AsyncSession, pk: Any) -> bool:
        repo = await customer_info_dao.delete(db, pk)
        if not repo:
            return False
        await db.commit()
        return True